package com.haoyeteng.sxbd.modular.system.controller;


import java.util.Date;
import java.util.List;

import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.code.kaptcha.Constants;
import com.haoyeteng.sxbd.core.base.controller.BaseController;
import com.haoyeteng.sxbd.core.common.exception.InvalidKaptchaException;
import com.haoyeteng.sxbd.core.log.LogManager;
import com.haoyeteng.sxbd.core.log.factory.LogTaskFactory;
import com.haoyeteng.sxbd.core.node.MenuNode;
import com.haoyeteng.sxbd.core.shiro.ShiroKit;
import com.haoyeteng.sxbd.core.shiro.ShiroAdmin;
import com.haoyeteng.sxbd.core.util.ApiMenuFilter;
import com.haoyeteng.sxbd.core.util.KaptchaUtil;
import com.haoyeteng.sxbd.core.util.ToolUtil;
import com.haoyeteng.sxbd.modular.business.model.MsgContent;
import com.haoyeteng.sxbd.modular.business.service.IMsgContentService;
import com.haoyeteng.sxbd.modular.system.model.Admin;
import com.haoyeteng.sxbd.modular.system.model.Role;
import com.haoyeteng.sxbd.modular.system.service.IMenuService;
import com.haoyeteng.sxbd.modular.system.service.IAdminService;
import static com.haoyeteng.sxbd.core.support.HttpKit.getIp;
/**
 * 登录控制器
 *
 * @author zhanglixiang
 * @Date 2017年1月10日 下午8:25:24
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IAdminService adminService;
    
    @Autowired
    private IMsgContentService msgContentService;

    /**
     * 跳转到主页
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
    	//获取菜单列表
    	Integer roleId = ShiroKit.getAdmin().getRoleId();
    	
    	if (ToolUtil.isEmpty(roleId)) {
    		ShiroKit.getSubject().logout();
            model.addAttribute("tips", "该用户没有角色，无法登陆");
            return "/login.html";
		}
    	
        
        List<MenuNode> menus = menuService.getMenusByRoleId(roleId);
        List<MenuNode> titles = MenuNode.buildTitle(menus);
        titles = ApiMenuFilter.build(titles);

        model.addAttribute("titles", titles);
        
        return "/index.html";
    }

    /**
     * 跳转到登录页面
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        if (ShiroKit.isAuthenticated() || ShiroKit.getAdmin() != null) {
            return REDIRECT + "/";
        } else {
            return "/login.html";
        }
    }

    /**
     * 点击登录执行的动作
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginVali() {

    	String account = super.getPara("username").trim();
        String password = super.getPara("password").trim();
        String remember = super.getPara("remember");

        //验证验证码是否正确
        if (KaptchaUtil.getKaptchaOnOff()) {
            String kaptcha = super.getPara("kaptcha").trim();
            String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if (ToolUtil.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
                throw new InvalidKaptchaException();
            }
        }

        Subject currentAdmin = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account, password.toCharArray());

        if ("on".equals(remember)) {
            token.setRememberMe(true);
        } else {
            token.setRememberMe(false);
        }

        currentAdmin.login(token);

        ShiroAdmin shiroAdmin = ShiroKit.getAdmin();
        super.getSession().setAttribute("shiroAdmin", shiroAdmin);
        super.getSession().setAttribute("adminname", shiroAdmin.getAccount());

        LogManager.me().executeLog(LogTaskFactory.loginLog(shiroAdmin.getId(), getIp()));

        ShiroKit.getSession().setAttribute("sessionFlag", true);
        
        //登陆成功后更新登陆信息
        Admin admin = adminService.selectOne(new EntityWrapper<Admin>().eq("account", account));
 		admin.setLoginip(ToolUtil.getRemoteAddr(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()));
 		admin.setLogintime(new Date());
 		adminService.updateById(admin);

        return REDIRECT + "/";
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logOut() {
        LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getAdmin().getId(), getIp()));
        ShiroKit.getSubject().logout();
        return REDIRECT + "/login";
    }
}
